const express = require("express");
const router = express.Router();
const mysql = require("mysql2/promise");
const configs = require("../config");
const CosUtil = require('../cosUtil'); 
const TtsUtil = require('../ttsUtils'); 
const path = require('path');
const fs = require('fs').promises;

// 创建数据库连接池
const pool = mysql.createPool({
  host: configs.mysql.host,
  user: configs.mysql.user,
  password: configs.mysql.password,
  database: configs.mysql.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});
const cosUtil = new CosUtil();
const ttsClient = new TtsUtil();
// 添加文件日志
router.post("/uploadfilelog", async (req, res) => {
  const { filepath, filesize, filetype, orgion, openid, id } = req.body;
  try {
      const connection = await pool.getConnection();

      let selectResults;

      if (id !== 0) {
          // 如果 ID 不为 0，查询该 ID 对应的数据
          const selectQuery = `SELECT * FROM yz_uploadfilelog WHERE id = ?`;
          [selectResults] = await connection.query(selectQuery, [id]);
          var d = await cosUtil.deleteFile(decodeURIComponent(selectResults[0].filepath.replace('https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/','')));
          console.log(d);
          const updateQuery = `UPDATE yz_uploadfilelog SET filepath = ?, filesize = ?, filetype = ?, orgion = ?, updatetime = NOW(), openid = ? WHERE id = ?`;
          const [updateResults] = await connection.query(updateQuery, [filepath, filesize, filetype, orgion, openid, id]);
      
          if (updateResults.affectedRows === 0) {
            connection.release();
            return res.status(404).json({
              status: "操作失败",
              code: 404,
              message: "File log not found",
            });
          }
         
          const [selectResults2] = await connection.query(selectQuery, [id]);
      
         // connection.release();
      
          if (selectResults2.length === 0) {
            return res.status(404).json({
              status: "操作失败",
              code: 404,
              message: "更新后未找到记录",
            });
          }
          res.json({
            status: "操作成功",
            code: 200,
            data: selectResults2[0], // 返回完整的记录
            d: d,
          });
      } else {
          // 如果 ID 为 0，插入新数据
          const insertQuery = `INSERT INTO yz_uploadfilelog (filepath, filesize, filetype, orgion, updatetime, openid) VALUES (?, ?, ?, ?, NOW(), ?)`;
          const [insertResults] = await connection.query(insertQuery, [filepath, filesize, filetype, orgion, openid]);

          // 查询刚插入的数据
          const selectQuery = `SELECT * FROM yz_uploadfilelog WHERE id = ?`;
          [selectResults] = await connection.query(selectQuery, [insertResults.insertId]);
      }

      connection.release();

      if (selectResults.length === 0) {
          return res.status(404).json({
              status: "操作失败",
              code: 404,
              message: "未找到记录",
          });
      }

      res.json({
          status: "操作成功",
          code: 200,
          data: selectResults[0], // 返回完整的记录
      });
  } catch (err) {
      console.error("Error adding file log:", err);
      res.status(500).json({
          status: "操作失败",
          code: 500,
          error: err.message,
      });
  }
});
// 获取所有文件日志
router.get("/uploadfilelog", async (req, res) => {
  try {
    const connection = await pool.getConnection();
    const query = `SELECT * FROM yz_uploadfilelog`;
    const [results] = await connection.query(query);
    connection.release();
    res.json({
      status: "操作成功",
      code: 200,
      data: results,
    });
  } catch (err) {
    console.error("Error fetching file logs:", err);
    res.status(500).json({
      status: "操作失败",
      code: 500,
      error: err.message,
    });
  }
});

// 获取单个文件日志
router.get("/uploadfilelog/:id", async (req, res) => {
  const { id } = req.params;
  try {
    const connection = await pool.getConnection();
    const query = `SELECT * FROM yz_uploadfilelog WHERE id = ?`;
    const [results] = await connection.query(query, [id]);
    connection.release();
    if (results.length === 0) {
      return res.status(404).json({
        status: "操作失败",
        code: 404,
        message: "File log not found",
      });
    }
    res.json({
      status: "操作成功",
      code: 200,
      data: results[0],
    });
  } catch (err) {
    console.error("Error fetching file log:", err);
    res.status(500).json({
      status: "操作失败",
      code: 500,
      error: err.message,
    });
  }
});

// 更新文件日志
router.put("/uploadfilelog/:id", async (req, res) => {
    const { id } = req.params;
    const { filepath, filesize, filetype, orgion, openid } = req.body;
    try {
      const connection = await pool.getConnection();
      // 更新数据
      const updateQuery = `UPDATE yz_uploadfilelog SET filepath = ?, filesize = ?, filetype = ?, orgion = ?, updatetime = NOW(), openid = ? WHERE id = ?`;
      const [updateResults] = await connection.query(updateQuery, [filepath, filesize, filetype, orgion, openid, id]);
  
      if (updateResults.affectedRows === 0) {
        connection.release();
        return res.status(404).json({
          status: "操作失败",
          code: 404,
          message: "File log not found",
        });
      }
  
      // 查询更新后的数据
      const selectQuery = `SELECT * FROM yz_uploadfilelog WHERE id = ?`;
      const [selectResults] = await connection.query(selectQuery, [id]);
  
      connection.release();
  
      if (selectResults.length === 0) {
        return res.status(404).json({
          status: "操作失败",
          code: 404,
          message: "更新后未找到记录",
        });
      }
  
      res.json({
        status: "操作成功",
        code: 200,
        data: selectResults[0], // 返回完整的记录
      });
    } catch (err) {
      console.error("Error updating file log:", err);
      res.status(500).json({
        status: "操作失败",
        code: 500,
        error: err.message,
      });
    }
  });

// 删除文件日志
router.delete("/uploadfilelog/:id", async (req, res) => {
  const { id } = req.params;
  try {
    const connection = await pool.getConnection();
    const query = `DELETE FROM yz_uploadfilelog WHERE id = ?`;
    const [results] = await connection.query(query, [id]);
    connection.release();
    if (results.affectedRows === 0) {
      return res.status(404).json({
        status: "操作失败",
        code: 404,
        message: "File log not found",
      });
    }
    res.json({
      status: "操作成功",
      code: 200,
      data: { message: "File log deleted successfully" },
    });
  } catch (err) {
    console.error("Error deleting file log:", err);
    res.status(500).json({
      status: "操作失败",
      code: 500,
      error: err.message,
    });
  }
});
// 确保临时目录存在
const tempDir = path.join(__dirname, 'temp');
(async () => {
  try {
    await fs.access(tempDir);
  } catch {
    await fs.mkdir(tempDir);
  }
})();
/**
 * 流式语音合成并上传COS
 * @api {post} /tts-stream 生成语音并上传COS
 * @apiParam {String} text 合成文本
 * @apiSuccess {String} audioUrl COS访问地址
 */
router.post('/tts-stream', async (req, res) => {
  let tempFilePath = null;
  
  try {
    // 参数校验
    const { text } = req.body;
    if (!text || text.length > 300) {
      return res.status(400).json({ 
        code: 400, 
        message: '文本不能为空且不超过300字' 
      });
    }

    // 合成语音
    const result = await ttsClient.synthesize(text);
    console.log('resultresultresultresultresult',result)
    //const audioBuffer = Buffer.from(result.Audio, 'base64');

    // 创建临时文件
    // const fileName = `tts-${Date.now()}.mp3`;
    // tempFilePath = path.join(tempDir, fileName);
    // await fs.writeFile(tempFilePath, audioBuffer);

    // // 上传到COS
    // const cosUrl = await cosUtil.uploadFile(tempFilePath, fileName);
    
    // // 清理临时文件
    // await fs.unlink(tempFilePath);
    // tempFilePath = null;

    // 返回结果
    res.json({
      status: "操作成功",
      code: 200,
      // data: {
      //   url: cosUrl,
      //   expires: new Date(Date.now() + 3600*1000).toISOString() // 示例有效期
      // },
      result
    });
    

  } catch (error) {
    // 错误时清理临时文件
    if (tempFilePath) {
      try { await fs.unlink(tempFilePath); } 
      catch (e) { console.error('临时文件清理失败:', e); }
    }
    
    console.error('[TTS Error]', error);
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});


module.exports = router;